import glob as gb
import os

class GetFileLocation(object):
    def __init__(self,projectlocation):
        self.projectLocation=projectlocation

    def _getNumEvent(self):
        N=len(gb.glob(self.projectLocation+"/SEISMOGRAM/*/"))
        return N
    nevent=property(fget=_getNumEvent)

    def _getEventsLocatin(self):
        events=gb.glob(self.projectLocation+"/SEISMOGRAM/*/")
        e=(event for event in events)
        return e
    geventsLocation=property(fget=_getEventsLocatin)

    def getEventsLocation(self):
        events=[e for e in self.geventsLocation]
        return events

    def getStationLocation(self,eventLocation):
        stationXMLPath = eventLocation + "XML/"
        stationsLocation = gb.glob(stationXMLPath + "*.xml")
        return stationsLocation

    def getSacLocation(self,eventLocation,station):
        sacPath = eventLocation + "SAC/"
        sacFiles = gb.glob(sacPath + "*" + station.split(".")[1] + "*.SAC")

        return self.sortFiles(sacFiles)

    def getSacZRTLocation(self,eventLocation,station):
        sacPath=eventLocation + "SACZRT/"
        sacFiles = gb.glob(sacPath + "*" + station.split(".")[1] + "*.SAC")
        return self.sortFiles(sacFiles)

    def getMseedLocation(self,eventLocation,station):
        mseedPath = eventLocation + "MSEED/"
        mseedFiles = gb.glob(mseedPath + "*" + station.split(".")[1] + "*.mseed")
        return mseedFiles

    def sortFiles(self,fileList):
        for file in fileList:
            if file.split(".")[3][-1]=="Z":
                fileList.remove(file)
                fileList.insert(0, file)
                break
        return fileList

    def getGenerator(self,function,**kwargs):
        s=function(**kwargs)
        gen=(s for s in s)
        return gen


    def fileCheck(self):
        for event in self.geventsLocation:
            stations = self.getGenerator(self.getStationLocation,eventLocation=event)
            for station in stations:
                mFiles = self.getMseedLocation(event, station)
                if len(mFiles) != 3:
                    os.remove(station)
                    for mFile in mFiles:
                        os.remove(mFile)
